package org.digitaldomination.speedclicker;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class startmenu extends Activity {

	private boolean mIsBound = false;
	private MusicService mServ;
	SharedPreferences preferences;
	boolean music;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.startmenu);

		Button play = (Button) findViewById(R.id.playbutton);
		Button highscore = (Button) findViewById(R.id.higscorebutton);
		Button setting = (Button) findViewById(R.id.settingsbutton);

		play.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent myIntent = new Intent(v.getContext(),
						speedclickerActivity.class);
				startActivityForResult(myIntent, 0);
			}
		});

		highscore.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent myIntent = new Intent(v.getContext(), highscore.class);
				startActivityForResult(myIntent, 0);
			}
		});

		setting.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent i = new Intent(startmenu.this, settings.class);
				startActivity(i);
			}
		});
	}

	private ServiceConnection Scon = new ServiceConnection() {

		public void onServiceConnected(ComponentName name, IBinder binder) {
			mServ = ((MusicService.ServiceBinder) binder).getService();
		}

		public void onServiceDisconnected(ComponentName name) {
			mServ = null;
		}
	};

	void doBindService() {
		bindService(new Intent(this, MusicService.class), Scon,
				Context.BIND_AUTO_CREATE);
		mIsBound = true;
	}

	void doUnbindService() {
		if (mIsBound) {
			unbindService(Scon);
			mIsBound = false;
		}
	}

	@Override
	protected void onResume() {
		super.onResume();

		preferences = PreferenceManager
				.getDefaultSharedPreferences(getBaseContext());
		music = preferences.getBoolean("music", true);
		Intent musics = new Intent();
		musics.setClass(this, MusicService.class);

		if (music) {
			doBindService();
			startService(musics);
		} else {
			doUnbindService();
			stopService(musics);
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mServ.mPlayer.isPlaying()) {
			mServ.stopMusic();
			doUnbindService();
		} else {
			doUnbindService();
		}
	}
}
